package com.yfbao.horizon.schedule.tk.sch;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ScheduledTaskAspect {

    @Autowired
    private DynamicMetrics dynamicMetrics;

    @Around("@annotation(scheduled)")
    public Object logScheduledTaskExecution(ProceedingJoinPoint joinPoint, Scheduled scheduled) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();
//        String className = joinPoint.getTarget().getClass().getName();
        StringBuilder builder =new StringBuilder();
        builder.append("Scheduled Task Triggered");
        builder.append(",Class: " + className);
        builder.append(",Method: " + methodName);
        builder.append(",Cron Expression: " + scheduled.cron());
        builder.append(",Fixed Rate: " + scheduled.fixedRate());
        builder.append(",Fixed Delay: " + scheduled.fixedDelay());

        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            result = joinPoint.proceed(); // 执行原任务逻辑
        }catch (Throwable e){
            long failedCost = (System.currentTimeMillis() - startTime);
            builder.append(",Task cost: " + failedCost + " ms");
//            dynamicMetrics.success(className+"_"+methodName);
            dynamicMetrics.failCostTime(className+"_"+methodName,failedCost);
            throw e;
        }
        long endTime = System.currentTimeMillis();
        long cost = (endTime - startTime);
        builder.append(",Task cost: " + cost + " ms");
//        dynamicMetrics.success(className+"_"+methodName);
        dynamicMetrics.sucessCostTime(className+"&"+methodName,cost);
//        log.warn(builder.toString());
        return result;
    }
}
